<template>
    <div class="profile-container">
        <!-- 左侧个人信息卡片 -->
        <el-card class="profile-card">
            <div class="avatar-box">
                <el-icon color="#409eff" :size="100">
                    <UserFilled v-if="user.avatar" />
                    <User v-else />
                </el-icon>
            </div>
            <el-descriptions column="1" border>
                <el-descriptions-item label="用户名">
                    <el-icon>
                        <User />
                    </el-icon> {{ user.userName }}
                </el-descriptions-item>
                <el-descriptions-item label="手机号">
                    <el-icon>
                        <Iphone />
                    </el-icon> {{ user.userPhone }}
                </el-descriptions-item>
                <el-descriptions-item label="用户邮箱">
                    <el-icon>
                        <Message />
                    </el-icon> {{ user.userEmail }}
                </el-descriptions-item>
                <el-descriptions-item label="所属组织">
                    <el-icon>
                        <OfficeBuilding />
                    </el-icon> {{ user.departmentName ? (user.departmentName + (user.positionName ? '/' +
                        user.positionName : '')) : '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="所属角色">
                    <el-icon>
                        <UserFilled />
                    </el-icon>
                    {{ userTypeText(user.userType) }}
                </el-descriptions-item>
                <el-descriptions-item label="创建日期">
                    <el-icon>
                        <Calendar />
                    </el-icon> {{ user.registerTime }}
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <!-- 右侧tab内容 -->
        <el-card class="profile-main">
            <el-tabs v-model="activeTab">
                <el-tab-pane label="基本资料" name="base">
                    <el-form :model="editForm" :rules="baseRules" ref="baseFormRef" label-width="100px"
                        class="profile-form">
                        <el-form-item label="真实姓名" prop="userNickname">
                            <el-input v-model="editForm.userNickname" />
                        </el-form-item>
                        <el-form-item label="手机号" prop="userPhone">
                            <el-input v-model="editForm.userPhone" />
                        </el-form-item>
                        <el-form-item label="邮箱" prop="userEmail">
                            <el-input v-model="editForm.userEmail" />
                        </el-form-item>
                        <el-form-item label="性别" prop="gender">
                            <el-radio-group v-model="editForm.gender">
                                <el-radio :label="1">男</el-radio>
                                <el-radio :label="2">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitBase">保存</el-button>
                            <el-button @click="resetBase">关闭</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="修改密码" name="password">
                    <el-form :model="pwdForm" :rules="pwdRules" ref="pwdFormRef" label-width="100px"
                        class="profile-form">
                        <el-form-item label="旧密码" prop="oldPwd">
                            <el-input v-model="pwdForm.oldPwd" type="password" show-password placeholder="请输入旧密码" />
                        </el-form-item>
                        <el-form-item label="新密码" prop="newPwd">
                            <el-input v-model="pwdForm.newPwd" type="password" show-password placeholder="请输入新密码" />
                        </el-form-item>
                        <el-form-item label="确认密码" prop="confirmPwd">
                            <el-input v-model="pwdForm.confirmPwd" type="password" show-password placeholder="请确认新密码" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitPwd">保存</el-button>
                            <el-button @click="resetPwd">关闭</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 错误提示弹窗 -->
        <el-dialog title="错误" v-model="errorDialogVisible" width="350px" show-close>
            <span>{{ errorMessage }}</span>
            <template #footer>
                <el-button type="primary" @click="errorDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { User, UserFilled, Iphone, Message, OfficeBuilding, Calendar } from '@element-plus/icons-vue'
import UserService from '../services/UserService'
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router'


const router = useRouter()

const user = reactive({
    userName: '',
    userNickname: '',
    userPhone: '',
    userEmail: '',
    gender: 1,
    departmentName: '',
    roleName: '',
    registerTime: '',
    userType: null,

})

const activeTab = ref('base')

const editForm = reactive({
    userNickname: '',
    userPhone: '',
    userEmail: '',
    gender: 1
})
const baseFormRef = ref()
const baseRules = {
    userNickname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    userPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    userEmail: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
}

const pwdForm = reactive({
    oldPwd: '',
    newPwd: '',
    confirmPwd: ''
})
const pwdFormRef = ref()
const pwdRules = {
    oldPwd: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newPwd: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    confirmPwd: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { validator: (rule, value) => value === pwdForm.newPwd, message: '两次输入密码不一致', trigger: 'blur' }
    ]
}

const errorDialogVisible = ref(false)
const errorMessage = ref('')

function showError(msg) {
    errorMessage.value = msg
    errorDialogVisible.value = true
}

function resetBase() {
    Object.assign(editForm, user)
    router.push('/news')
}
function resetPwd() {
    pwdForm.oldPwd = ''
    pwdForm.newPwd = ''
    pwdForm.confirmPwd = ''
    router.push('/news')

}

async function submitBase() {
    baseFormRef.value.validate(async (valid) => {
        if (!valid) return
        try {
            console.log(editForm)
            const res = await UserService.updateProfile(user.userId, {
                userNickname: editForm.userNickname,
                userPhone: editForm.userPhone,
                userEmail: editForm.userEmail,
                gender: editForm.gender
            })
            if (res.code === 200) {
                ElMessage.success('保存成功')
                Object.assign(user, editForm)
            } else {
                showError(res.message || '保存失败')
            }
        } catch (e) {
            showError(e.message || '保存失败')
        }
    })
}

async function submitPwd() {
    pwdFormRef.value.validate(async (valid) => {
        if (!valid) return
        try {
            const res = await UserService.changePassword({
                userId: user.userId,
                oldPassword: pwdForm.oldPwd,
                newPassword: pwdForm.newPwd
            })
            if (res.code === 200) {
                resetPwd()
                activeTab.value = 'base'
                ElMessage.success('修改密码成功')
            } else {
                showError(res.message || '修改密码失败')
            }
        } catch (e) {
            showError(e.message || '修改密码失败')
        }
    })
}

function userTypeText(type) {
    if (type === 0) return '普通用户';
    if (type === 1) return '企业管理员';
    if (type === 2) return '超级管理员';
    return '-';
}

onMounted(async () => {
    UserService.loadCurrentUser();
    const local = JSON.parse(localStorage.getItem('currentUser') || '{}')
    Object.assign(user, local)
    Object.assign(editForm, user)
})
</script>

<style scoped>
.profile-container {
    display: flex;
    gap: 32px;
    padding: 32px;
    background: #f7f8fa;
    min-height: 50vh;
}

.profile-card {
    width: 340px;
    min-width: 300px;
    padding: 24px 0 0 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.avatar-box {
    display: flex;
    justify-content: center;
    margin-bottom: 16px;
}

.profile-main {
    flex: 1;
    min-width: 400px;
    padding: 24px 32px;
}

.profile-form {
    max-width: 500px;
    margin-top: 24px;
}
</style>